package com.yrh.controller;

import com.yrh.bean.TCategory;
import com.yrh.bean.TProduct;
import com.yrh.service.TCategoryService;
import com.yrh.service.TProductService;
import com.yrh.service.impl.TCategoryServiceImpl;
import com.yrh.service.impl.TProductServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*菜品信息控制层*/
@WebServlet("/ProductServlet/*")
public class ProductServlet extends BaseServlet {
    private TProductService service=new TProductServiceImpl();
    private TCategoryService tservice=new TCategoryServiceImpl();
    //去菜品信息页面
    public void gotoProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台的参数封装为JavaBean
        Map<String, String[]> map = request.getParameterMap();
        TProduct p=new TProduct();
        BeanUtils.populate(p,map);
        //携带数据回去渲染
        List<TProduct> pList = service.allProduct(p,0,0);
        //分页操作
        //分页操作
        int size=2;//每页的数据量
        int totalPage=pList.size()%size==0?pList.size()/size:pList.size()/size+1;//计算出多少页
        int nowPage=1;//默认显示第一页;
        if (request.getParameter("nowPage")!=null){
            nowPage=Integer.parseInt(request.getParameter("nowPage"));
        }
        List<TCategory> tList = tservice.allCategory();
        pList=service.allProduct(p,nowPage,size);
        request.setAttribute("tList",tList);
        request.setAttribute("nowPage",nowPage);
        request.setAttribute("totalPage",totalPage);
        request.setAttribute("pList",pList);
        request.setAttribute("categoryName",p.getCategoryName());
        request.setAttribute("productName",p.getProductName());
        request.getRequestDispatcher("/product.jsp").forward(request,response);
    }
    /*去菜单页面*/
    public void gotoMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        TProduct product=new TProduct();
        BeanUtils.populate(product,map);
       //查询所有上架菜品
        List<TProduct> tList = service.allProduct(product, 0, 0);
        ArrayList<TProduct> tProducts = new ArrayList<>();
        for (TProduct products : tList) {
            if ("Y".equals(products.getProductStatus())){
                tProducts.add(products);
            }
        }
        //查询所有分类
        List<TCategory> tCategories = tservice.allCategory();
        request.setAttribute("tList",tProducts);
        request.setAttribute("tCList",tCategories);
        request.setAttribute("categoryName",product.getCategoryName());
        request.getRequestDispatcher("/menu.jsp").forward(request,response);
    }



    //上传图片
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
       // 创建一个DiskFileItemfactory工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 创建一个ServletFileUpload核心对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 解决上传文件名中文乱码
        sfu.setHeaderEncoding("utf-8");

        String filename = "";
        // 解析request对象
        try {
            FileItem fileItem = sfu.parseRequest(request).get(0);
            filename = uploadFile(fileItem);
            response.getWriter().print(filename);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            response.getWriter().print("");
        }

    }
    //保存到本地磁盘
    // 将上传文件表单项封装
    private String uploadFile(FileItem fileItem) {
        // 如果上传表单项
        // 得到文件输入流
        // 创建物理目录路径
        String realPath = "E:\\java框架学习\\JavaWeb-第三阶段\\upload";
        // 根据该路径创建一个目录对象
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();// 创建一个指定的目录
        }
        // 得到上传的名子
        String filename = fileItem.getName();
        if (filename != null) {
            // 得到文件后缀
            String extend = filename.substring(filename.indexOf("."));
            // 重写生成一个唯一的文件名
            filename = System.currentTimeMillis() + extend;
        }
        // 上传文件,自动删除临时文件
        try {
            fileItem.write(new File(realPath, "/" + filename));
        } catch (Exception e) {
            filename = "";
        }
        return filename;
    }
    //验证菜品名
    public void chePName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台的参数
        String name = request.getParameter("name");
        TProduct t=new TProduct();
        t.setProductName(name);
        TProduct tt = service.byPName(t);
        if (tt!=null){
            response.getWriter().println(1);
        }else {
            response.getWriter().println(-1);
        }
    }
    //添加菜品信息
    public void addProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
       //将前台传的参数进行封装
        Map<String, String[]> map = request.getParameterMap();
        TProduct p=new TProduct();
        BeanUtils.populate(p,map);
        int i = service.updateProduct(p);
        //去尾页
        TProduct pp=new TProduct();
        //携带数据回去渲染
        List<TProduct> pList = service.allProduct(pp,0,0);
        int size=2;//每页的数据量
        int totalPage=pList.size()%size==0?pList.size()/size:pList.size()/size+1;//计算出多少页
        int nowPage=totalPage;//默认显示第一页;
        System.out.println("nowPage = " + nowPage);
        pList=service.allProduct(pp,nowPage,size);
        request.setAttribute("nowPage",nowPage);
        request.setAttribute("totalPage",totalPage);
        request.setAttribute("pList",pList);
        if (i>0){
            response.getWriter().println(nowPage);
        }else {
            response.getWriter().println(-1);
        }
    }
    //修改菜品信息
    public void updateProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将前台传的参数进行封装
        Map<String, String[]> map = request.getParameterMap();
        TProduct p=new TProduct();
        BeanUtils.populate(p,map);
        int i = service.updateProduct(p);
        if (i>0){
            response.getWriter().println(1);
        }else {
            response.getWriter().println(-1);
        }
    }
    //删除菜品
    public void del(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String productId = request.getParameter("productId");
        String nowPage = request.getParameter("nowPage");
        TProduct product=new TProduct();
        product.setProductId(Integer.parseInt(productId));
        int i = service.delProduct(product);
        TProduct pp=new TProduct();
        //携带数据回去渲染
        List<TProduct> pList = service.allProduct(pp,0,0);
        int size=2;//每页的数据量
        int totalPage=pList.size()%size==0?pList.size()/size:pList.size()/size+1;//计算出多少页
        int ss=Integer.parseInt(nowPage);
       if (ss>totalPage){
            System.out.println("123456 = " + 123456);
            response.getWriter().println(0);
        }
        else if (i>0){
            response.getWriter().println(1);
        } else {
            response.getWriter().println(-1);
        }
    }
    //上架或下架
    public void updateStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将前台传的参数进行封装
        Map<String, String[]> map = request.getParameterMap();
        TProduct p=new TProduct();
        BeanUtils.populate(p,map);
        int i = service.updateStatus(p);
        if (i>0){
            response.getWriter().println(1);
        }else {
            response.getWriter().println(-1);
        }
    }
}
